package com;

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.imageio.ImageIO;

public class Teacher {
	public static int WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width; // 获得屏幕宽带
	public static int HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height; // 获得屏幕高度
	public static final int SCREENPORT = 54529;
	public static final int CMDPORT = 54528;
	private static boolean isCast;
	private static InetAddress addr;
	private static DatagramSocket ds;

	static {
		try {
			addr = InetAddress.getByName("255.255.255.255");
			ds = new DatagramSocket();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void sendCmd(String cmdStr) {
		byte[] tmp = new byte[1024];
		DatagramPacket cmd = new DatagramPacket(tmp, tmp.length, addr, CMDPORT);
		cmd.setData(cmdStr.getBytes());
		try {
			ds.send(cmd);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static String receiveCmd(){
		byte[] tmp=new byte[1024];
		DatagramPacket cmd=new DatagramPacket(tmp, tmp.length);
		try {
			ds.receive(cmd);
			String s=new String(cmd.getData(), 0, cmd.getLength());
			return s;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public static void startCast() {
		sendCmd("start");
		isCast = true;
		new Thread() {
			@Override
			public void run() {
				while (isCast) {
					try {
						Robot robot = new Robot();
						BufferedImage image = robot.createScreenCapture(new Rectangle(WIDTH, HEIGHT));
						ByteArrayOutputStream os = new ByteArrayOutputStream();
						ImageIO.write(image, "jpg", os);
						InputStream is = new ByteArrayInputStream(os.toByteArray());
						int c = 0;
						byte[] buf = new byte[1024];
						while ((c = is.read(buf)) != -1) {
							if(isCast==false)break;
							DatagramPacket dp = new DatagramPacket(buf, c, addr, SCREENPORT);
							ds.send(dp);
						}
						DatagramPacket dp = new DatagramPacket("end".getBytes(), 3, addr, SCREENPORT);
						ds.send(dp);
						Thread.sleep(100);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	public static void stopCast() {
		isCast = false;
		sendCmd("stop");
	}
}
